const project = require("../dao/projectDao");
const { handleProject } = require("../utils/tool");
const validate = require("validate.js");
const { ValidationError } = require("../utils/errors");

//添加项目
const addPorject = async (info) => {
  info.description = info.description.join(";");
  const rule = {
    name: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
    description: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
    url: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
    github: {
      type: "string",
    },
    thumb: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
    order: {
      presence: {
        allowEmpty: false,
      },
      type: "integer",
    },
  };
  const validation = validate.validate(info, rule);
  if (!validation) {
    const result = await project.addPorject(info);
    return handleProject(result);
  } else {
    throw new ValidationError("数据验证错误");
  }
};

//修改项目
const updateProject = async (id, info) => {
  if (info.description) {
    info.description = info.description.join(";");
  }
  const rule = {
    name: {
      type: "string",
    },
    description: {
      type: "string",
    },
    url: {
      type: "string",
    },
    github: {
      type: "string",
    },
    thumb: {
      type: "string",
    },
    order: {
      type: "integer",
    },
  };
  const validation = validate.validate(info, rule);
  if (!validation) {
    const result = await project.updateProject(id, info);
    return handleProject(result);
  } else {
    throw new ValidationError("数据验证错误");
  }
};

//删除项目
const deleteProject = async (id) => {
  return await project.deleteProject(id);
};

//获取项目
const getProject = async () => {
  const result = await project.getProject();
  return handleProject(result);
};

module.exports = {
  addPorject,
  updateProject,
  deleteProject,
  getProject,
};
